from flask import jsonify, render_template, Blueprint, request

from index.fear_greed import get_fear_greed_data_for_chart
from util.log_util import get_the_logger

logger = get_the_logger(__name__)

market_sentiment_bp = Blueprint('market_sentiment', __name__)

# ---------------------- API接口：返回恐慌指数数据 ----------------------
@market_sentiment_bp.route("/api/market/sentiment", methods=["GET"])
def market_sentiment_data():
    """
    返回恐慌指数数据用于图表展示
    """
    # 获取时间范围参数，默认为'all'
    time_range = request.args.get('range', 'all')
    
    try:
        # 获取用于图表展示的恐慌指数数据
        data = get_fear_greed_data_for_chart(time_range)
        
        return jsonify({
            "success": True,
            "data": data
        })
    except Exception as e:
        logger.error(f"获取恐慌指数数据失败: {e}")
        return jsonify({
            "success": False,
            "error": f"获取数据失败: {str(e)}"
        })

# ---------------------- 前端页面路由：渲染恐慌指数图表页面 ----------------------
@market_sentiment_bp.route("/market/sentiment")
def market_sentiment_page():
    """返回恐慌指数图表页面"""
    return render_template("market_sentiment.html")